<?php

namespace addons\cos\controller;

use app\common\exception\UploadException;


use Qcloud\Cos\Client;
use think\addons\Controller;


/**
 * COS云储存
 *
 */
class Index extends Controller
{

    protected $cosConfig = [];

    public function initialize()
    {
        parent::initialize();
        $config = get_addons_config('addon','cos');
        $this->cosConfig = array(
            'region'      => $config['region'],
            'schema'      => 'https', //协议头部，默认为http
            'credentials' => array(
                'secretId'  => $config['secretId'],
                'secretKey' => $config['secretKey']
            )
        );
    }

    private function __cosClient(){
        $config = get_addons_config('addon','cos');
        return $cosClient = new Client(
            array(
                'region'      => $config['region'],
                'schema'      => 'https', //协议头部，默认为http
                'credentials' => array(
                    'secretId'  => $config['secretId'],
                    'secretKey' => $config['secretKey']
                )
            )
        );
    }

    public function uploads()
    {
        //获取储存桶对象
        $cosClient = $this->__cosClient();
        $config = get_addons_config('addon','cos');

        //获取上传的文件
        $files =  request()->file('file');
        $fileAddList = [];
        foreach ($files as $file){
            if($file->getSize() > $config['maxsize']){
               $this->error('超出文件上传大小');
            }
            $fileName = md5(uniqid()).'.'.pathinfo($file->getOriginalName(), PATHINFO_EXTENSION);
            $key =  date('Y').date('m').'/'.date('d').'/'.$fileName;
            //上传
            try {
                $result = $cosClient->Upload(
                    $bucket =$config['bucket'],//存储桶名称
                    $key = $key, //此处的 key 为对象键
                    $body = fopen($file->getFileInfo()->getPathname(), "rb")//文件数据
                );
                // 请求成功
                $url = $config['cdnurl'] ? $config['cdnurl'] .'/'.  $key : 'https://' . $result['Location'];

                $temp['title'] = $fileName;
                $temp['md5'] = $file->md5();
                $temp['mime_type'] = $file->getOriginalMime();
                $temp['ext'] = $file->getOriginalExtension();
                $temp['size'] = $file->getSize();
                $temp['storage'] = 'cos';
                $temp['path'] = $url;
                $temp['user_type'] = '1';
                $temp['user_id'] = '1'; // 后台用户
                if (!empty($temp)) {
                    $bl = (new \app\admin\model\routine\Attachment)->save($temp);
                    if (!$bl) {
                        throw new UploadException(__('No rows added'));
                    }else{
                        array_push($fileAddList,$temp);
                    }
                }
            } catch (\Exception $e) {
                // 请求失败
               $this->error('上传失败');
            }
        }
        $this->success('上传成功'.count($fileAddList).'个文件','',$fileAddList);
    }

    public function delete($path): \think\response\Json
    {
        //获取删除图的key
        $key = $path;
        //获取储存桶对象
        $cosClient = $this->__cosClient();

        //删除
        try {
            $result = $cosClient->deleteObject(array(
                'Bucket' => $this->bucket,//存储桶名称
                'Key' => $key,
            ));
            // 请求成功
            return json([
                "msg"=>"删除成功",
                "data"=>[
                    "RequestId"=>$result['RequestId'],
                    "Bucket"=>$result['Bucket'],
                    "Key"=>$result['Key'],
                    "Location"=>$result['Location'],
                ]
            ]);
        } catch (\Exception $e) {
            // 请求失败
            return json([
                "msg" =>"删除失败",
                "data"=>[],
            ]);
            //echo $e;
        }
    }

    public function index()
    {
        return '暂无前台页面';
    }

    public function getFileName($file, $md5 = '', $sha1 = '', $suffix = '')
    {
        $var = [
            '{year}'=> date('Y'),
            '{month}'=> date('m'),
            '{day}'=> date('d'),
            '{hour}'=> date('H'),
            '{minute}'=> date('i'),
            '{second}'=> date('s'),
            '{md5}'=> $md5?$md5:$file->md5(),
            '{sha1}'=> $sha1?$sha1:$file->sha1(),
            '{random}'=> get_random_str(16),
            '{suffix}'=> $suffix?$suffix:'.'.$file->extension(),
        ];
        $config = get_addons_config('addon','cos');
        return str_replace(array_keys($var),array_values($var), $config['savekey']);
    }

}
